<template>
  <div :id="`node${id}`" class="node" ref="node" :style="nodeStyle" @mousedown="handleMouseDown">
    <p class="node-title" :style="titleStyle">{{ title }}</p>
    <div class="node-container">
      <div class="node-inputs">
        <pin
          v-for="(pin, index) in inputs"
          :key="pin.title"
          v-bind="pin"
          :isInput="true"
          :nodeIndex="nodeIndex"
          :pinIndex="index"
        />
      </div>
      <div class="node-spacer"></div>
      <div class="node-outputs">
        <pin
          v-for="(pin, index) in outputs"
          :key="pin.title"
          v-bind="pin"
          :isInput="false"
          :nodeIndex="nodeIndex"
          :pinIndex="index"
        />
      </div>
    </div>
    <div v-if="isSelected" class="node-selected"></div>
  </div>
</template>

<script>
import Pin from './Pin.vue';
import * as chroma from 'chroma-js';
import { mapMutations } from 'vuex';

export default {
  components: { Pin },

  props: {
    isSelected: Boolean,
    id: Number,
    nodeIndex: Number,
    title: String,
    color: String,
    pos: Array,
    inputs: Array,
    outputs: Array,
  },

  methods: {
    ...mapMutations(['dragStart']),

    handleMouseDown(ev) {
      this.dragStart({
        type: 'NODES',
        x: ev.clientX,
        y: ev.clientY,
        index: this.nodeIndex,
        ctrl: ev.ctrlKey,
      });
    },
  },

  computed: {
    nodeStyle() {
      return {
        left: `${this.pos[0]}px`,
        top: `${this.pos[1]}px`,
      };
    },

    titleStyle() {
      const color = getComputedStyle(document.body).getPropertyValue(`--vscode-charts-${this.color}`);
      const chromaColor = chroma.valid(color) ? chroma(color) : chroma(props.color);
      return {
        backgroundColor: chromaColor.luminance(Math.min(chromaColor.luminance(), 0.25)).hex(),
      };
    },
  },
};
</script>

<style scoped>
.node {
  min-width: 100px;
  position: absolute;
  box-sizing: border-box;
  box-shadow: 2px 2px 4px var(--vscode-widget-shadow), -2px -2px 4px var(--vscode-widget-shadow);
  background-color: var(--vscode-editorWidget-background);
  border: thin solid var(--vscode-editorWidget-border);
}

.node-selected {
  pointer-events: none;
  box-sizing: border-box;
  position: absolute;
  left: -1px;
  top: -1px;
  right: -1px;
  bottom: -1px;
  border: 2px solid var(--vscode-focusBorder);
}

.node-title {
  color: white;
  user-select: none;
  margin: 0;
  padding-left: 10px;
  height: 20px;
}

.node-container {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
}

.node-inputs {
  text-align: left;
  margin-left: 5px;
}

.node-outputs {
  text-align: right;
  margin-right: 5px;
}

.node-spacer {
  width: 30px;
}
</style>
